package seggio;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;


public class GestoreRichieste extends Thread {

    private Socket ss;
    private final String ip;
    /**
     * 
     * @param richiesta 
     */
    public GestoreRichieste(String ipCabLib) {
        this.ip = ipCabLib;
    }

    /**
     * 
     */   
    @Override
    public void run() {
         try {
            
            ss = new Socket(ip, 10000);
             
            //apro il buffer in lettura scrittura
            BufferedReader br = new BufferedReader(new InputStreamReader(ss.getInputStream()));
            BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(ss.getOutputStream()));

            String command = br.readLine();
            String res = protocollo.CmdParserSeggio.parseAndRunCommand(command);
            
            wr.write(res, 0, res.length());

            wr.flush();
            wr.close();
            br.close();
            ss.close();
            
        } catch (IOException e) {
            System.err.println("Errore connessione client dal socket: " + ss);        
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(GestoreRichieste.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(GestoreRichieste.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(GestoreRichieste.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                ss.close();
            } catch (IOException e) {
            }
            System.out.println("Output closed.");
        }
    }
}